package org.cttic.visualization.visualization.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
import org.cttic.visualization.visualization.common.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author shkstart
 * @create 2020-04-29 10:47
 */
@Component
public class DataUtil {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public realTimeData sendDataUtil(String value) {
        JSONObject data = ParseJsonDataUtil.getJsonData(value);
        String vehicleId = data.getString("vehicleId");
        int vehicleIdColor = data.getIntValue("vehicleIdColor");
        String transTime = data.getString("transTime");
        int pointType = data.getIntValue("pointType");
        String gantryId = data.getString("gantryId");
        String gantryName = data.getString("gantryName");
        String latitude = data.getString("latitude");
        String longitude = data.getString("longitude");
        String endLat = data.getString("endLat");
        int enExFlag = data.getIntValue("enExFlag");
        String provinceId = null;
        String roadSectionId = null;
        String pileNumber = null;
        String direction = null;
        String billAmount =null;
//********************************
        sectionBillQuery sectionBillQuery = new sectionBillQuery();
        sectionBillQuery.setVehPlate(vehicleId);
        sectionBillQuery.setPlateColor(vehicleIdColor);
        sectionBillQuery.setCurrentsTime(DateUtil.timeToT(transTime));
        //查询mysql 门架基础信息表 T_GANTRY_MOUNTING

        if (pointType == 3) {

            String sql = "SELECT gantryId,provinceId,tollIntervals,roadSectionId,pileNumber FROM `T_GANTRY_MOUNTING` " +
                    "where  gantryId= '" +
                    gantryId + "'";
            List<T_mysqlData> mysqlData = jdbcTemplate.query(sql, new BeanPropertyRowMapper(T_mysqlData.class));
            T_mysqlData t_mysqlData = mysqlData.get(0);
            provinceId = t_mysqlData.getProvinceId();
            roadSectionId = t_mysqlData.getRoadSectionId();
            pileNumber = t_mysqlData.getPileNumber();
            direction = gantryId.substring(14, 15);
            //G000444001001010040
            sectionBillQuery.setSectionDirection(gantryId.substring(14, 15));

            sectionBillQuery.setAdminCode(t_mysqlData.getProvinceId());        //省域编码
            sectionBillQuery.setSectionCode(t_mysqlData.getRoadSectionId());       //路段编号
            String tollIntervals = t_mysqlData.getTollIntervals();
            sectionBillQuery.setTollIntervals(tollIntervals);      //路段单元编码
//            if (tollIntervals.contains("|")) {
//                String[] splitData = tollIntervals.split("|");
//                int billMile = 0;   //单位米
//                for (int i = 0; i <= splitData.length; i++) {
//                    billMile = billMile + Integer.parseInt(splitData[i]);
//                }
//                //单位 km
//                sectionBillQuery.setBillMile((float) billMile / 1000);            //里程数
//            }

//            sectionBillQuery.setBillMile(0.0f);
            sectionBillQuery.setVehCode(1);              //计费车型
            sectionBillQuery.setActualAxleNum(1);       //实际轴数
            sectionBillQuery.setMediumType("1");
//        String urlString ="http://192.168.195.30:9042/hmop/mmp/api/tb/getJiangXiNationalBilling?"
//                +sectionBillQuery.toString();
//            RestTemplate restTemplate = new RestTemplate();
//        ResponseEntity<String> responseEntity = restTemplate.getForEntity(urlString, String.class);
//        String body = responseEntity.getBody();
//
//        retSectionData retSectionData = JSONObject.parseObject(body, retSectionData.class);
//         billAmount = retSectionData.getData().getBillAmount();

        } else if (pointType == 1) {
            String sql = "SELECT stationId,provinceId,stakeNum FROM `T_STATION` " +
                    "where  stationId= '" +
                    gantryId + "'";


            //List<Object> mysqlData = jdbcTemplate.query(sql, new BeanPropertyRowMapper(Object.class));
           // Object t_mysqlData = mysqlData.get(0);
            List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
            Map<String, Object> stringObjectMap = maps.get(0);
//            sectionId = stringObjectMap.get("stationId").toString();
            provinceId = stringObjectMap.get("provinceId").toString();
            pileNumber = stringObjectMap.get("stakeNum") == null ? "": stringObjectMap.get("stakeNum").toString();
//            roadSectionId = t_mysqlData.getRoadSectionId();
            if (enExFlag == 1) {
                direction = "1";
            } else if (enExFlag == 2) {
                direction = "2";
            }
        }
        realTimeData realTimeData = new realTimeData();
        realTimeData.setCmd("122");

        realTimeData.setProvinceId(provinceId);     //todo 省编码
//        realTimeData.setSessionId();
        realTimeData.setVehId(vehicleId + "_" + vehicleIdColor);
        realTimeData.setVehStatus("0");
        realTimeData.setTransTime(DateUtil.timeToT(transTime));
        if (pointType == 3) {
            realTimeData.setPointType("1");
        } else if (pointType == 1) {
            realTimeData.setPointType("3");
        }
        realTimeData.setGantryId(gantryId);
        realTimeData.setGantryName(gantryName);

        if (enExFlag != 3) {
            realTimeData.setEnExFlag(enExFlag + "");
        }
        realTimeData.setSectionCode(roadSectionId);        //todo 路段编号
        realTimeData.setPileNum(pileNumber);            //todo 门架桩号
        realTimeData.setDirection(direction);          //todo 门架方向
        realTimeData.setLat(latitude);
        realTimeData.setLng(longitude);
        double x = Math.random() * 10;
        if(x>5){
            realTimeData.setTransFee("**.**");      //todo 屏显金额
        }else {
            realTimeData.setTransFee("***.**");      //todo 屏显金额
        }
//        realTimeData.setTransFee(billAmount);
        realTimeData.setEndLat(endLat);
        return realTimeData;


    }


    public static List<itineraryQueryData.Trip> itineraryQueryDataUtil(FindIterable<Document> documents, String feeFlag) {
        itineraryQueryData itineraryQueryData = new itineraryQueryData();
        org.cttic.visualization.visualization.common.itineraryQueryData.Trip trip = new itineraryQueryData.Trip();
        List<itineraryQueryData.Trip> list = new ArrayList<>();
        MongoCursor<Document> iterator = documents.iterator();
        while (iterator.hasNext()) {
            String json = iterator.next().toJson();
            JSONObject data = ParseJsonDataUtil.getJsonData(json);
            String endLat = data.getString("endLat");
            String vehicleId = data.getString("vehicleId");
            int vehicleIdColor = data.getIntValue("vehicleIdColor");
            String entryStation = data.getString("entryStation");
            String entryStationId = data.getString("entryStationId");
            String entryTime = data.getString("entryTime");
            int isOnline = data.getIntValue("isOnline");
            if (isOnline == 1) {
                String exitTime = data.getString("exitTime");
                String exitStationId = data.getString("exitStationId");
                String exitStation = data.getString("exitStation");
                trip.setExitGantryId(exitStationId);
                trip.setExitGantryName(exitStation);
                trip.setExitTime(exitTime);
            }

            trip.setEndLat(endLat);
            trip.setVehPlate(vehicleId);
            trip.setVehPlateColor(vehicleIdColor + "");
            trip.setEnGantryName(entryStation);
            trip.setEnGantryId(entryStationId);
            trip.setEnTime(entryTime);
            trip.setIsOnline(isOnline + "");

            trip.setVehStatus("0");
            //产生一个100以内的整数:int x=(int)(Math.random()*100);
            if(StrUtil.isNotBlank(feeFlag)){
                if (Integer.parseInt(feeFlag) == 1) {
                    trip.setTotalReceivableAmt("***.**");
                    trip.setTotalDiscountAmt("***.**");
                }
            }

            list.add(trip);
//            itineraryQueryData.setTripList(list);
            return list;
        }
        return null;
    }

    public static List<trackQueryData.vehLocation> trackQueryDataUtil(FindIterable<Document> documents) {
        List<trackQueryData.vehLocation> list = new ArrayList<>();
        MongoCursor<Document> iterator = documents.iterator();
        while (iterator.hasNext()) {
            trackQueryData.vehLocation vehLocation = new trackQueryData.vehLocation();
            String json = iterator.next().toJson();
            JSONObject data = ParseJsonDataUtil.getJsonData(json);
            String transTime = data.getString("reportTime");
            String lat = data.getString("latitude");
            String lng = data.getString("longitude");

            String vec = data.getString("velocity");
            String dir = data.getString("direction");
            String dis = data.getString("totalDistance");
            vehLocation.setTransTime(DateUtil.timeToT(transTime));
            vehLocation.setDir(dir);
            vehLocation.setDis(dis);
            vehLocation.setLat(lat);
            vehLocation.setLng(lng);
            vehLocation.setVec(vec);
            list.add(vehLocation);
        }
        return list;
    }

    public  List<RouteIdentificationData.Identification> IdentificationQueryDataUtil(FindIterable<Document> documents,RouteIdentificationData rtData) {

        List<RouteIdentificationData.Identification> list= new ArrayList<>();
        RouteIdentificationData.Identification identification = new RouteIdentificationData.Identification();
        MongoCursor<Document> iterator = documents.iterator();
        int pointType = 0;
        String transTime= null;
        String endLat= null;
        String gantryId= null;
        String gantryName= null;
        String enExFlag= null;
        String provinceId = null;
        String sectionId = null;
        String pileNumber = null;
        String direction = null;
        String SectionCode=null;
        String upAndDown=null;
        String tollIntervals=null;
        String billMile=null;
        String lat=null;
        String lng =null;
        while (iterator.hasNext()){
            String json = iterator.next().toJson();
            JSONObject data = ParseJsonDataUtil.getJsonData(json);
            transTime = data.getString("transTime");
            endLat = data.getString("endLat");
            gantryId = data.getString("gantryId");
            gantryName = data.getString("gantryName");
            enExFlag = data.getString("enExFlag");
            pointType=data.getIntValue("pointType");
            upAndDown=data.getString("upAndDown");
            lat = data.getString("latitude");
            lng = data.getString("longitude");




        if (pointType == 3) {

            String sql = "SELECT gantryId,provinceId,tollIntervals,roadSectionId,pileNumber FROM `T_GANTRY_MOUNTING` " +
                    "where  gantryId= '" +
                    gantryId + "'";

            List<T_mysqlData> mysqlData = jdbcTemplate.query(sql, new BeanPropertyRowMapper(T_mysqlData.class));
            T_mysqlData t_mysqlData = mysqlData.get(0);
            provinceId = t_mysqlData.getProvinceId();
            sectionId = t_mysqlData.getRoadSectionId();
            pileNumber = t_mysqlData.getPileNumber();
            SectionCode=t_mysqlData.getRoadSectionId();
            tollIntervals = t_mysqlData.getTollIntervals();


        } else if (pointType == 1) {
            String sql = "SELECT stationId,provinceId,stakeNum FROM `T_STATION` " +
                    "where  stationId= '" +
                    gantryId + "'";

            List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
            Map<String, Object> stringObjectMap = maps.get(0);
//            sectionId = stringObjectMap.get("stationId").toString();
            provinceId = stringObjectMap.get("provinceId").toString();
            pileNumber = stringObjectMap.get("stakeNum") == null ? "": stringObjectMap.get("stakeNum").toString();
//            roadSectionId = t_mysqlData.getRoadSectionId();

        }
        identification.setTransTime(transTime);
        identification.setEndLat(endLat);
        identification.setVehStatus("0");
        identification.setGantryId(gantryId);
        identification.setGantryName(gantryName);
        identification.setEnExFlag(enExFlag);

        identification.setSectionCode(SectionCode);
        identification.setPileNum(pileNumber);
        identification.setDirection(upAndDown);
        identification.setTollIntervals(tollIntervals);
        identification.setBillMile("0.0");
        identification.setLat(lat);
        identification.setLng(lng);
        identification.setProvinceId(provinceId);
        identification.setSectionId(sectionId);
        identification.setReceivableAmount("***.**");
        identification.setDiscountAmount("*.**");
        identification.setBillAmount("***.**");
        }

        list.add(identification);
        if(endLat!=null){
            rtData.setIsOnline("0");
        }else {
            rtData.setIsOnline("1");
        }
        return list;
        }

    public static String getPointType(int gantryType){
        String pointType=null;
        //收费站
        if(gantryType==1){
            pointType="3";
        }else if(gantryType==2){
            pointType="1";
        }else if(gantryType==3){
            pointType="2";
        }
        return pointType;
    }
}